﻿using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore;
using YDT_PaymentService.Domain.Entities;

namespace YDT_PaymentService.Infrastructure.Data
{
    /// <summary>
    /// 支付数据库上下文 - 负责与数据库交互
    /// </summary>
    public class PaymentDbContext : DbContext
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public PaymentDbContext(DbContextOptions<PaymentDbContext> options) : base(options) { }

        /// <summary>支付表</summary>
        public DbSet<Payment> Payments { get; set; }

        /// <summary>
        /// 配置模型 - 定义数据库表结构和关系
        /// </summary>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 配置支付实体
            modelBuilder.Entity<Payment>(entity =>
            {
                // 主键配置
                entity.HasKey(e => e.Id);

                // 属性配置
                entity.Property(e => e.PaymentPrice)
                    .HasColumnType("decimal(18,2)"); // 支付金额使用decimal(18,2)

                entity.Property(e => e.PaymentStatus)
                    .HasConversion<string>() // 枚举转换为字符串存储
                    .HasMaxLength(20);

                entity.Property(e => e.PaymentType)
                    .HasConversion<string>() // 枚举转换为字符串存储
                    .HasMaxLength(20);

                entity.Property(e => e.PaymentMethod)
                    .IsRequired()
                    .HasMaxLength(50); // 支付方式最大长度50

                entity.Property(e => e.PaymentRemark)
                    .HasMaxLength(500); // 支付备注最大长度500

                entity.Property(e => e.PaymentUrl)
                    .HasMaxLength(1000); // 支付URL最大长度1000

                entity.Property(e => e.PaymentReturnUrl)
                    .IsRequired()
                    .HasMaxLength(1000); // 支付回调URL最大长度1000

                entity.Property(e => e.PaymentCode)
                    .IsRequired()
                    .HasMaxLength(50); // 支付单号最大长度50

                entity.Property(e => e.PaymentErrorNo)
                    .HasMaxLength(50); // 支付错误编号最大长度50

                entity.Property(e => e.PaymentErrorInfo)
                    .HasMaxLength(500); // 支付错误信息最大长度500

                // 索引配置
                entity.HasIndex(e => e.PaymentCode)
                    .IsUnique(); // 支付单号唯一索引

                entity.HasIndex(e => e.OrderId)
                    .IsUnique(); // 订单ID唯一索引（一个订单对应一个支付记录）

                entity.HasIndex(e => e.UserId); // 用户ID索引
                entity.HasIndex(e => e.PaymentStatus); // 支付状态索引
                entity.HasIndex(e => e.CreateTime); // 创建时间索引
            });
        }

        /// <summary>
        /// 保存更改 - 自动设置更新时间
        /// </summary>
        public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            // 自动设置更新时间
            var entries = ChangeTracker.Entries()
                .Where(e => e.Entity is Payment &&
                           (e.State == EntityState.Modified || e.State == EntityState.Added));

            foreach (var entityEntry in entries)
            {
                ((Payment)entityEntry.Entity).UpdateTime = DateTime.UtcNow;
            }

            return await base.SaveChangesAsync(cancellationToken);
        }
    }
}
